package com.jerry.weixing.servlet;

import com.jerry.weixing.domain.*;
import com.jerry.weixing.util.TransFromUtil;
import com.jerry.weixing.util.WeiUtil;
import com.jerry.weixing.util.httpUtil;
import net.sf.json.JSONObject;
import org.dom4j.DocumentException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Jerry
 * @Description
 * @date 2016-10-09
 */
public class WeixingServlet extends HttpServlet {

    private static final String MessageText = "text";
    private static final String MessageEvent = "event";
    private static final String MessageNews = "news";
    private static final String MessageSubscribe = "subscribe";
    private static final String MessageUnsubscribe = "unsubscribe";
    private static final String MessageLocation = "location";
    private static final String MessageScancode= "scancode_push";
    private static final String MessageView = "VIEW";
    private static final String MessageClick ="CLICK";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        AcessToken acessToken = httpUtil.getToken();
        try {
            Map<String, Object> map = TransFromUtil.transXmlToMap(req);
            String FromUserName = (String) map.get("FromUserName");
            String ToUserName = (String) map.get("ToUserName");
            String Content = (String) map.get("Content");
            String MsgType = (String) map.get("MsgType");
            String Event = (String) map.get("Event");

            PrintWriter pw = resp.getWriter();
            String messageXml = null;
            if (MessageText.equals(MsgType)) {
                if ("1".equals(Content)) {
                    TextMessage message = new TextMessage();
                    message.setCreateTime(new Date().getTime());
                    message.setFromUserName(ToUserName);
                    message.setToUserName(FromUserName);
                    message.setMsgType(MessageText);
                    message.setContent("你好啊你的回复是1: " + "欢迎你关注这个网站");
                    messageXml = TransFromUtil.transMessageToXml(message);
                } else if ("2".equals(Content)) {
                    NewsMessage newsMessage = new NewsMessage();
                    newsMessage.setCreateTime(new Date().getTime());
                    newsMessage.setFromUserName(ToUserName);
                    newsMessage.setToUserName(FromUserName);
                    newsMessage.setMsgType(MessageNews);
                    newsMessage.setArticleCount(2);

                    List<News> news = new ArrayList<>();
                    News new1 = new News();
                    new1.setTitle("这是一个图文标题1");
                    new1.setDescription("你好啊你的回复是你好啊你的回复你好啊你的回复是你好啊你的回复是你好啊你的回复是");
                    new1.setPicUrl("http://mytest.tunnel.2bdata.com/WeXin/image/9bc93f61fa74bf159f5ea793cec6bef5d546e26a85691-r236HF_fw658.jpg");
                    new1.setUrl("https://www.baidu.com");

                    News new2 = new News();
                    new2.setTitle("这是一个图文标题2");
                    new2.setDescription("你好啊你的回复是你好啊你的回复你好啊你的回复是你好啊你的回复是你好啊你的回复是");
                    new2.setPicUrl("http://mytest.tunnel.2bdata.com/WeXin/image/9c13c40ef27caefdf86c59048cde9f0d1d861f8d5db505-TF4D1F_fw658.jpg");
                    new2.setUrl("wow.178.com");
                    news.add(new1);
                    news.add(new2);
                    newsMessage.setArticles(news);
                    messageXml = TransFromUtil.tranNewsToXml(newsMessage);
                    System.out.println(messageXml);
                }else if("3".equals(Content)){
                    messageXml = TransFromUtil.initImage(ToUserName,FromUserName);
                    System.out.println(messageXml);
                }else if("4".equals(Content)){
                    messageXml = TransFromUtil.initMusic(ToUserName,FromUserName);
                    System.out.println(messageXml);
                }else if("5".equals(Content)){
                    httpUtil.deleteMenu(acessToken.getAccess_token());
                }
            } else if (MessageEvent.equals(MsgType)) {
                if (MessageSubscribe.equals(Event)) {

                    String menu =  JSONObject.fromObject(httpUtil.initMenu()).toString();
                    int result = httpUtil.createMenu(acessToken.getAccess_token(),menu);
                    if(result == 0){
                        System.out.println("菜单创建成功");
                    }else{
                        System.out.println("菜单创建失败：原因是"+result);
                    }
                    messageXml = TransFromUtil.init(ToUserName,FromUserName);
                }else if(MessageClick.equals(Event)){
                    messageXml = TransFromUtil.init(ToUserName,FromUserName);
                }else if(MessageView.equals(Event)){
                    String url = (String)map.get("EventKey");
                    messageXml = TransFromUtil.initContent(ToUserName,FromUserName,url);
                }else if(MessageScancode.equals(Event)){
                    String key = (String)map.get("EventKey");
                    messageXml = TransFromUtil.initContent(ToUserName,FromUserName,key);
                }
            }else if(MessageLocation.equals(MsgType)){
                String label = (String)map.get("Label");
                messageXml = TransFromUtil.initContent(ToUserName,FromUserName,label);
            }
            System.out.println(messageXml);
            pw.write(messageXml);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");
        String signature = req.getParameter("signature");

        PrintWriter pw = null;
        try {
            pw = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (WeiUtil.checkNumber(signature, timestamp, nonce)) {
            pw.print(echostr);
        }

    }
}
